package com.lxd.controller;

import com.lxd.entity.LoginRequest;
import com.lxd.entity.RegisterRequest;
import com.lxd.entity.TokenUserInfoDto;
import com.lxd.entity.enums.ResponseCodeEnum;
import com.lxd.entity.vo.ResponseVO;
import com.lxd.entity.vo.UserInfoVO;
import com.lxd.exception.BusinessException;
import com.lxd.redis.RedisUtil;
import com.lxd.service.UserService;
import com.lxd.utils.StringTools;
import com.wf.captcha.ArithmeticCaptcha;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author Dongdong
 * @注释
 */
@RestController("loginController")
@RequestMapping("/account")
public class AccountController extends ABaseController {
    private static final Logger logger = LoggerFactory.getLogger(AccountController.class);

    @Autowired
    private RedisUtil redis;

    @Autowired
    private UserService userService;

    /**
     * 验证码功能
     * @return
     */
    @RequestMapping("/checkCode")
    public ResponseVO checkCode() {
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(100, 42);
        String code = captcha.text(); // 获取运算的公式：3+2=?
        String checkCodeKey = UUID.randomUUID().toString();// 验证码的唯一标识uuid
        String checkCodebase64 = captcha.toBase64();//验证码图片
        logger.info("验证码是{}", code);
        // 将验证码存入redis中  key：验证码唯一标识 value：验证码
        redis.set(checkCodeKey,code, 5, TimeUnit.MINUTES);
        HashMap<String, String> result = new HashMap<>();
        result.put("checkCode", checkCodebase64);
        result.put("checkCodeKey", checkCodeKey);
        System.out.println(result.get(checkCodeKey));
        return getSuccessResponseVO(result);
    }

    /**
     * 注册
     *
     * @param email
     * @param username
     * @param password
     * @param realName
     * @return
     */
    @PostMapping("/register")
    public ResponseVO register(@RequestBody RegisterRequest registerRequest) {
        //从redis中校验验证码
        String checkCodeKey = registerRequest.getCheckCodeKey();
        try {
            if (StringTools.isEmpty(checkCodeKey)){
                throw new BusinessException("验证码不能为空");
            }
            String code = (String) redis.get(checkCodeKey);
            if (StringTools.isEmpty(code)){
                throw new BusinessException("验证码已过期！！！");
            }
            if (!code.equals(registerRequest.getCheckCode())){
                throw new BusinessException("验证码错误！！！");
            }

            userService.register(registerRequest);
        }finally {
            redis.del(checkCodeKey);
        }


        return getSuccessResponseVO("注册成功！！！");


    }

    /**
     *     登录
     */
    @PostMapping("/login")
    public ResponseVO login(@RequestBody LoginRequest loginRequest) {
        String checkCodeKey = loginRequest.getCheckCodeKey();
        try {
            //从redis中校验验证码
            if (StringTools.isEmpty(checkCodeKey)){
                throw new BusinessException("验证码不能为空");
            }
            String code = (String) redis.get(checkCodeKey);
            if (StringTools.isEmpty(code)){
                throw new BusinessException("验证码已过期！！！");
            }
            if (!code.equals(loginRequest.getCheckCode())){
                throw new BusinessException("验证码错误！！！");
            }

            //校验登录，并生成token 体
            TokenUserInfoDto tokenUserInfoDto = userService.login(loginRequest);

            UserInfoVO userInfoVO = new UserInfoVO();
            userInfoVO.setUserId(tokenUserInfoDto.getUserId());
            userInfoVO.setEmail(tokenUserInfoDto.getEmail());
            userInfoVO.setUserRealName(tokenUserInfoDto.getUserRealName());
            userInfoVO.setUserName(tokenUserInfoDto.getUserName());
            userInfoVO.setAdmin(tokenUserInfoDto.getAdmin());
            userInfoVO.setToken(tokenUserInfoDto.getToken());
            return getSuccessResponseVO(userInfoVO);
        }finally {
            redis.del(checkCodeKey);
        }

    }
}
